import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

/**
 * @typedef {Object} RouteMeta
 * @property {string} title - 页面标题
 * @property {boolean} [requiresAuth] - 是否需要认证
 * @property {number[]} [roles] - 允许访问的角色列表
 * @property {string} [icon] - 图标名称
 * @property {boolean} [keepAlive] - 是否需要缓存
 * @property {boolean} [hideTabbar] - 是否隐藏底部导航
 */

/**
 * @type {import('vue-router').RouteRecordRaw[]}
 */
const routes = [
  // 认证相关
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/index.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  // 医生模块
  {
    path: '/doctor',
    component: () => import('../views/doctor/layout.vue'),
    redirect: '/doctor/home',
    meta: {
      requiresAuth: true,
      roles: [2]
    },
    children: [
      {
        path: 'home',
        component: () => import('@/views/doctor/index.vue'),
        meta: { title: '工作台' }
      },
      {
        path: 'profile',
        component: () => import('@/views/doctor/profile/index.vue'),
        meta: { title: '我的' }
      },
      {
        path: 'consultation/detail/:id',
        component: () => import('@/views/doctor/consultation/detail.vue'),
        meta: { title: '问诊详情' }
      },
      {
        path: 'profile/edit',
        component: () => import('@/views/doctor/profile/profile.vue'),
        meta: { title: '编辑资料' }
      },
      {
        path: 'password',
        component: () => import('@/views/doctor/profile/password.vue'),
        meta: { title: '修改密码' }
      },
      {
        path: 'consultation',
        name: 'DoctorConsultation',
        component: () => import('@/views/doctor/consultation/index.vue'),
        meta: {
          title: '全部问诊',
          requiresAuth: true,
          roles: [2]
        }
      },
      {
        path: 'patients',
        name: 'DoctorPatients',
        component: () => import('../views/doctor/patients/index.vue'),
        meta: {
          title: '患者管理',
          requiresAuth: true,
          roles: [2]
        }
      },
      {
        path: 'patients/:id',
        name: 'PatientDetail',
        component: () => import('../views/doctor/patients/detail.vue'),
        meta: {
          title: '患者详情',
          requiresAuth: true,
          roles: [2]
        }
      }
    ]
  },
  // 患者模块
  {
    path: '/',
    component: () => import('../layout/index.vue'),
    redirect: '/home',
    meta: {
      requiresAuth: true,
      roles: [3]
    },
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('../views/home/index.vue'),
        meta: {
          title: '首页',
          requiresAuth: true,
          roles: [3]
        }
      },
      {
        path: 'consultation',
        name: 'Consultation',
        component: () => import('../views/consultation/doctor-list.vue'),
        meta: {
          title: '选择医生',
          requiresAuth: true,
          roles: [3]
        }
      },
      {
        path: 'consultation/list',
        name: 'ConsultationList',
        component: () => import('../views/consultation/index.vue'),
        meta: {
          title: '选择医生',
          requiresAuth: true,
          roles: [3]
        }
      },
      {
        path: 'consultation/detail/:id',
        name: 'DoctorDetail',
        component: () => import('../views/consultation/doctor-detail.vue'),
        meta: {
          title: '医生详情',
          requiresAuth: true,
          roles: [3],
          hideTabbar: true
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/user/index.vue'),
        meta: {
          title: '我的',
          requiresAuth: true,
          roles: [3]
        }
      },
      {
        path: '/user/profile',
        name: 'ProfileProfile',
        component: () => import('../views/user/profile.vue'),
        meta: {
          title: '个人资料',
          requiresAuth: true,
          roles: [3]
        }
      },
      {
        path: '/user/password',
        name: 'ProfilePassword',
        component: () => import('../views/user/password.vue'),
        meta: {
          title: '修改密码',
          requiresAuth: true,
          roles: [3]
        }
      }
    ]
  },
  // 健康模块
  {
    path: '/health',
    component: () => import('../layout/index.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'record',
        name: 'HealthRecord',
        component: () => import('../views/health/record.vue'),
        meta: {
          title: '健康记录',
          keepAlive: true
        }
      },
      {
        path: 'health',
        name: 'Health',
        component: () => import('@/views/health/index.vue'),
        meta: {
          title: '健康管理',
          requiresAuth: true,
          roles: [1, 2, 3]
        }
      },
      {
        path: 'daily',
        name: 'DailyRecord',
        component: () => import('@/views/health/DailyRecord.vue'),
        meta: {
          title: '录入健康数据',
          requiresAuth: true,
          roles: [3],
          hideTabbar: true
        }
      }
    ]
  },

  // 文章模块
  {
    path: '/article',
    name: 'ArticleList',
    component: () => import('../views/article/index.vue'),
    meta: {
      title: '健康科普',
      requiresAuth: true,
      hideTabbar: true
    }
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('../views/article/detail.vue'),
    meta: {
      title: '文章详情',
      hideTabbar: true
    }
  },
  // 错误页面
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('../views/error/403.vue'),
    meta: {
      title: '无权访问',
      hideTabbar: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('../views/error/404.vue'),
    meta: {
      title: '页面不存在',
      hideTabbar: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  },
  {
    path: '/health/records',
    name: 'HealthRecords',
    component: () => import('../views/health/HealthRecords.vue'),
    meta: {
      title: '健康记录',
      requiresAuth: true,
      roles: [3],
      hideTabbar: true
    }
  },
  {
    path: '/consultation/chat/:id',
    // path: '/consultation/user/chat/:id',
    name: 'ConsultationChat',
    component: () => import('@/views/consultation/chat.vue'),
    meta: {
      title: '问诊对话',
      requiresAuth: true,
      roles: [3],
      hideTabbar: true
    }
  },
  {
    path: '/family',
    name: 'Family',
    component: () => import('@/views/family/index.vue'),
    meta: {
      title: '家庭成员',
      requiresAuth: true,
      roles: [1, 2, 3],
      hideTabbar: true
    }
  },
  // 聊天页面
  {
    path: '/chat',
    name: 'chat',
    component: () => import('@/views/chat/index.vue'),
    meta: {
      title: '问诊对话',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        resolve(savedPosition)
      } else {
        resolve({ top: 0 })
      }
    })
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const store = useUserStore()
  const token = store.token
  const roleId = store.userInfo?.roleId

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 健康管理` : '健康管理'

  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }

  // 根据角色限制访问
  if (to.meta.roles && !to.meta.roles.includes(roleId)) {
    // 如果用户是患者(roleId === 3)，访问医生路由，重定向到首页
    if (roleId === 3 && to.path.startsWith('/doctor')) {
      next('/home')
      return
    }
    // 如果用户是医生(roleId === 2)，访问患者路由，重定向到医生首页
    if (roleId === 2 && to.path.startsWith('/patient')) {
      next('/doctor/home')
      return
    }
    // 其他未授权访问，显示403
    if (!to.meta.roles.includes(roleId)) {
      next('/403')
      return
    }
  }

  next()
})

export default router

